package com.happy3w.ssp.schoolmatehome.component.image;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Getter
@Slf4j
public class Canvas implements AutoCloseable {
    private final BufferedImage canvas;
    private Graphics2D g2d;
    private final int offsetX;
    private final int offsetY;

    public Canvas(int width, int height, int offsetX, int offsetY) {
        this.offsetX = offsetX;
        this.offsetY = offsetY;
        canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = canvas.createGraphics();
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, width, height);
    }

    public byte[] buildImageBytes() {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(canvas, "png", baos);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("Error exporting preview image", e);
            return null;
        }

    }

    public Canvas drawImage(BufferedImage image, Point location) {
        g2d.drawImage(image, location.x + offsetX, location.y + offsetY, null);
        return this;
    }

    public void drawText(String text, Point location) {
        g2d.drawString(text, location.x + offsetX, location.y + offsetY);
    }

    @Override
    public void close() throws Exception {
        if (g2d != null) {
            g2d.dispose();
            g2d = null;
        }
    }
}
